﻿using Microsoft.Extensions.Logging;
using Quartz;
using System.Reflection;

namespace PmSoft.Core.Job.Quartz;

/// <summary>
/// Quartz 调度器提供者，实现作业调度逻辑
/// </summary>
public class QuartzSchedulerProvider : IJobSchedulerProvider
{
	private readonly ISchedulerFactory _schedulerFactory;
	private readonly ILogger<QuartzSchedulerProvider> _logger;
	private IScheduler _scheduler;

	/// <summary>
	/// 构造函数，注入 Quartz 调度器工厂和日志记录器
	/// </summary>
	/// <param name="schedulerFactory">Quartz 调度器工厂</param>
	/// <param name="logger">日志记录器</param>
	public QuartzSchedulerProvider(ISchedulerFactory schedulerFactory, ILogger<QuartzSchedulerProvider> logger)
	{
		_schedulerFactory = schedulerFactory;
		_logger = logger;
	}

	/// <summary>
	/// 启动调度器并调度所有作业
	/// </summary>
	/// <param name="jobTypes">作业类型的集合</param>
	public async Task StartAsync(IEnumerable<Type> jobTypes)
	{
		_scheduler = await _schedulerFactory.GetScheduler();
		await _scheduler.Start();
		_logger.LogInformation("Quartz 调度器已启动");

		foreach (var jobType in jobTypes)
		{
			var jobAttribute = jobType.GetCustomAttribute<JobScheduleAttribute>();
			if (jobAttribute != null)
			{
				var jobKey = new JobKey(jobAttribute.Name, "DefaultGroup");
				IJobDetail job = JobBuilder.Create<QuartzJobExecutor>()
					.WithIdentity(jobKey)
					.UsingJobData("JobType", jobType.FullName)
					.SetJobData(new JobDataMap { { "JobType", jobType } }) // 传递 Type 对象
					.Build();

				ITrigger trigger = TriggerBuilder.Create()
					.WithIdentity($"{jobAttribute.Name}_Trigger", "DefaultGroup")
					.WithCronSchedule(jobAttribute.Schedule)
					.Build();

				await _scheduler.ScheduleJob(job, trigger);
				_logger.LogInformation("作业 {JobName} 已调度，Cron: {CronExpression}", jobAttribute.Name, jobAttribute.Schedule);
			}
		}
	}

	/// <summary>
	/// 停止调度器，关闭 Quartz 实例
	/// </summary>
	public async Task StopAsync()
	{
		if (_scheduler != null)
		{
			await _scheduler.Shutdown();
			_logger.LogInformation("Quartz 调度器已停止");
		}
	}
}
